/*
 * FILE                : spi.c
 * DESCRIPTION         : This file is iCore3 spi driver demo.
 * Author              : XiaomaGee@Gmail.com
 * Copyright           :
 *
 * History
 * --------------------
 * Rev                 : 0.00
 * Date                : 11/21/2015
 *
 * create.
 * --------------------
 */
//-----------------Include files-------------------------//
 
#include "..\include\spi.h"
#include "..\fwlib\inc\stm32f4xx_gpio.h"
#include "..\fwlib\inc\stm32f4xx_rcc.h"
#include <stdio.h>

//---------------- Function Prototype ------------------//

static int initialize(void);
static int write_nbyte(int number,  char * buf);
static  char write_byte( char data);

//-----------------Variable-----------------------------//  
SPI_SIMULATE_T spi = {
	.initialize = initialize,
	.write_nbyte = write_nbyte,
	.write_byte = write_byte
};
//-----------------Function-----------------------------//

/*
 * Name								: initialize
 * Description				: ---
 * Author							: XiaomaGee.
 *
 * History
 * -------------------
 * Rev								: 0.00
 * Date								: 08/26/2012
 * 
 * create.
 * -------------------
 */

static int initialize(void)
{	
	GPIO_InitTypeDef GPIO_uInitStructure;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE);
	SPI_CS_OUTPUT;
	SPI_CLK_OUTPUT;
	SPI_MOSI_OUTPUT;
	SPI_MISO_INPUT;
	
	SPI_CS_ON;
	SPI_CS_OFF;
	SPI_CLK_ON;
	SPI_CLK_OFF;
	SPI_M0SI_ON;
	SPI_MOSI_OFF;
	SPI_MISO_DATA;
		
	return 0;
}
/*
 * Name								: initialize_spi1
 * Description				: ---
 * Author							: XiaomaGee.
 *
 * History
 * -------------------
 * Rev								: 0.00
 * Date								: 08/26/2012
 * 
 * create.
 * -------------------
 */

static  char write_byte(  char data)
{
	int i;
	int j;
	unsigned char temp = 0;
	
	for(i = 0;i < 7;i++){
		if (data & 0x80){
			SPI_M0SI_ON;
		}else{
			SPI_MOSI_OFF;
		}
		
		SPI_CLK_OFF;		

		for (j = 0; j < 5; j++);
		if(SPI_MISO_DATA)temp |= 1;
		else temp |= 0;

		SPI_CLK_ON;
		for(j = 0;j < 5;j++);
		data <<= 1;
		temp <<= 1;	
	}
	
	if (data & 0x80){
		SPI_M0SI_ON;
	}else{
		SPI_MOSI_OFF;
	}
		
	SPI_CLK_OFF;		

	for (j = 0; j < 5; j++);
	if(SPI_MISO_DATA)temp |= 1;
	else temp |= 0;

	SPI_CLK_ON;
	for(j = 0;j < 5;j++);
	
	return temp;
}
/*
 * Name								: write
 * Description				: ---
 * Author							: XiaomaGee.
 *
 * History
 * -------------------
 * Rev								: 0.00
 * Date								: 08/26/2012
 * 
 * create.
 * -------------------
 */
static int write_nbyte(int number,  char * buf)
{
	int i;
	SPI_CS_ON;
	for (i = 0; i < number; i++){
		buf[i] = write_byte(buf[i]);
	}
	SPI_CS_OFF;
	return 0;
}

